package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 西门凌兰
 * @version 1.0
 */
@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //当前集合用于存放从begin到end范围内的每天的日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        if (begin.isBefore(end) || begin.equals(end)) {
            while (!begin.equals(end)) {
                //日期计算
                begin = begin.plusDays(1);
                dateList.add(begin);
            }
        }

        List<Double> doubleList = new ArrayList<>();
        //select sum(amount) from orders where status = 5 and order_time > begin and order_time < end
        for (LocalDate localDate : dateList) {
            Map map = new HashMap();
            map.put("begin",LocalDateTime.of(localDate, LocalTime.MIN));
            map.put("end",LocalDateTime.of(localDate,LocalTime.MAX));
            map.put("status", Orders.COMPLETED);

            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0 : turnover;
            doubleList.add(turnover);
        }

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(doubleList,","))
                .build();
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //1.先得到时间集合
        List<LocalDate> localDates = new ArrayList<>();
        if (begin.isBefore(end) || begin.equals(end)) {
            localDates.add(begin);
            while (!begin.equals(end)) {
                begin = begin.plusDays(1);
                localDates.add(begin);
            }
        }
        //2.得到老用户集合,顺便得到新用户集合
        //select count(*) from user where create_time <= ?
        //select count(*) from user where create_time between ? and ?
        List<Integer> oldUsers = new ArrayList<>();
        List<Integer> newUsers = new ArrayList<>();
        for (LocalDate localDate : localDates) {
            Integer oldCount = userMapper.countOldUsers(LocalDateTime.of(localDate,LocalTime.MAX));
            Integer newCount = userMapper.countNewUsers(LocalDateTime.of(localDate,LocalTime.MIN),
                                                        LocalDateTime.of(localDate,LocalTime.MAX));
            oldCount = oldCount == null ? 0 : oldCount;
            newCount = newCount == null ? 0 : newCount;
            oldUsers.add(oldCount);
            newUsers.add(newCount);
        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(localDates,","))
                .totalUserList(StringUtils.join(oldUsers,","))
                .newUserList(StringUtils.join(newUsers,","))
                .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //1.得到时间集合
        List<LocalDate> localDates = new ArrayList<>();
        if (begin.isBefore(end) || begin.equals(end)) {
            localDates.add(begin);
            while (!begin.equals(end)) {
                begin = begin.plusDays(1);
                localDates.add(begin);
            }
        }

        //select count(*) from orders where order_time < endTime 得到订单总数
        //select count(*) from orders where order_time < endTime and status = ? 得到有效订单总数

        //select count(*) from orders where order_time between beginTime and endTime 得到每天的订单数
        //select count(*) from orders where order_time between beginTime and endTime and status = ? 得到每天的有效订单数
        Map map = new HashMap();
        map.put("end",LocalDateTime.of(end,LocalTime.MAX));
        //得到总订单数
        Integer totalOrderCount = orderMapper.countByMap(map);
        //得到总有效订单数
        map.put("status",Orders.COMPLETED);
        Integer validOrderCount = orderMapper.countByMap(map);
        //得到订单完成率

        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }

        //每日订单数集合
        List<Integer> orderCountList = new ArrayList<>();
        //每日有效订单数集合
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate localDate : localDates) {
            map = new HashMap();
            map.put("begin",LocalDateTime.of(localDate,LocalTime.MIN));
            map.put("end",LocalDateTime.of(localDate,LocalTime.MAX));
            Integer orderCount = orderMapper.countByMap(map);
            map.put("status",Orders.COMPLETED);
            Integer validOrder = orderMapper.countByMap(map);

            orderCount = orderCount == null ? 0 : orderCount;
            validOrder = validOrder == null ? 0 : validOrder;

            orderCountList.add(orderCount);
            validOrderCountList.add(validOrder);
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(localDates,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 查询销量top10菜品
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        /*
            SELECT `name` `name`,COUNT(number) number
            FROM `order_detail`
            WHERE order_id IN (
	        SELECT id FROM orders
	        WHERE order_time between ? AND ?
            )
            GROUP BY `name`
            ORDER BY number DESC
            LIMIT 0,10
         */
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        //1.查询前十菜品名称
        List<String> nameList = orderDetailMapper.getTop10Name(beginTime,endTime);

        //2.查询前十数量
        List<Integer> numberList = orderDetailMapper.getTop10Number(beginTime,endTime);
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessDate(HttpServletResponse response) throws IOException {
        //1.查询数据库，获取营业数据
        LocalDate begin = LocalDate.now().plusDays(-30);
        LocalDate end = LocalDate.now().plusDays(-1);
        //查询概览数据
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN),
                                                                        LocalDateTime.of(end, LocalTime.MAX));
        //2.通过POI将数据写入到Excel中
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        //基于模板文件创建一个新的Excel文件
        XSSFWorkbook excel = new XSSFWorkbook(is);
        //获取表格sheet页
        XSSFSheet sheet = excel.getSheet("Sheet1");
        //填充数据--时间
        sheet.getRow(1).getCell(1).setCellValue("时间: " + begin + "至" + end);
        //填充第四行
        XSSFRow row = sheet.getRow(3);
        row.getCell(2).setCellValue(businessData.getTurnover());
        row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
        row.getCell(6).setCellValue(businessData.getNewUsers());
        //填充第5行
        row = sheet.getRow(4);
        row.getCell(2).setCellValue(businessData.getValidOrderCount());
        row.getCell(4).setCellValue(businessData.getUnitPrice());
        //填充明细数据
        for (int i = 0; i < 30; i++) {
            //得到天数
            LocalDate localDate = begin.plusDays(i);
            //得到每天的数据
            businessData = workspaceService.getBusinessData(LocalDateTime.of(localDate, LocalTime.MIN),
                    LocalDateTime.of(localDate, LocalTime.MAX));
            //得到行对象
            row = sheet.getRow(7 + i);
            //填充数据
            row.getCell(1).setCellValue(localDate.toString());
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(3).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(5).setCellValue(businessData.getUnitPrice());
            row.getCell(6).setCellValue(businessData.getNewUsers());
        }
        //3.通过输出流将Excel文件下载到客户端浏览器
        ServletOutputStream outputStream = response.getOutputStream();
        excel.write(outputStream);

        //关闭资源
        excel.close();
        outputStream.close();
        is.close();

    }
}
